package indi.xliuovo.coursedesign.musicplayer;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with Android Studio
 *
 * @author Tang Xiao
 */
class MyThread extends Thread {
    static String baseUrl = "http://121.40.211.91:8080/";
    String params; // 传入参数
    Map<String, Object> result = new ConcurrentHashMap<>(); // 获取返回结果

    // 数据处理
    void toParams(String path, Map<String, String> loginUserInfo) {
        StringBuilder str = new StringBuilder(path);
        boolean isHead = true;
        for (Map.Entry<String, String> item : loginUserInfo.entrySet()) { // 增强 for 循环
            if (isHead) {
                str.append("?");
                isHead = false;
            } else {
                str.append("&");
            }
            str.append(item.getKey()).append("=").append(item.getValue()); // 完善Url
        }
        params = str.toString(); // 转换为 String 对象
    }

    @Override
    public void run() {
        try {
            URL url = new URL(baseUrl + params);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = connection.getInputStream();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(500);
            connection.setReadTimeout(500);
            InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(reader);
            System.out.println(connection.getResponseCode());
            StringBuffer buffer = new StringBuffer();
            String temp = null;
            while ((temp = bufferedReader.readLine()) != null) {
                buffer.append(temp);
            }
            bufferedReader.close();
            reader.close();
            inputStream.close();
            System.out.println("请求成功！");
            System.out.println(buffer.toString());
            // 获取返回结果
            Gson gson = new Gson();
            Map<String, Object> map = new ConcurrentHashMap<>();
            map = gson.fromJson(buffer.toString(), map.getClass()); // Json 转 Map
            if (((Double) map.get("code")).intValue() == 400) {
                map.put("msg", java.net.URLDecoder.decode(map.get("msg").toString()));
            }
            if (((Double) map.get("code")).intValue() == 200) {
                map.put("msg", java.net.URLDecoder.decode(map.get("msg").toString()));
            }
            result = map;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("No");
            System.out.println(e);
        }
    }
}